package com.iticit.config;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class JettyServer {

	private final static String CONTEXT_PATH = "/";
	private final static String MAPPING_URL = "/*";
	//private final static int SERVER_PROT = 8888;
	private Integer port;
	public JettyServer(Integer port) {
		this.port = port;
	}
	public void run() throws Exception {
		Server server = new Server(port);
		server.setHandler(servletContextHandler(webApplicationContext()));
		server.start();
		server.join();
	}
	
	
	private WebApplicationContext webApplicationContext() {
		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.register(AppConfiguration.class);
		return context;
	}
	
	private ServletContextHandler servletContextHandler(WebApplicationContext context) {
		ServletContextHandler handler = new ServletContextHandler();
		handler.setContextPath(CONTEXT_PATH);
		handler.addServlet(new ServletHolder(new DispatcherServlet(context)), MAPPING_URL);
		handler.addEventListener(new ContextLoaderListener(context));
		return handler;
	}
	
}
